package com.frank.work;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author 小石潭记
 * @date 2021/12/20 19:30
 * @Description: ${todo}
 */
@Service
@Slf4j
public class GroupTaskService {

    private ThreadPoolExecutor threadPoolExecutor;

    private ArrayBlockingQueue<? super Runnable> arrayBlockingQueue;
    /**
     * 队列大小
     */
    private static final int queueSize = 100;
    /**
     *  核心线程数
     */
    private static final int corePoolSize = 10;
    /**
     * 最大线程数
     */
    private static final int maxPoolSize = 30;
    /**
     * 时间
     */
    private static final int keepAliveTime = 2;


    @PostConstruct
    public void init() {
        arrayBlockingQueue = new ArrayBlockingQueue<>(queueSize);
        threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS,
                (BlockingQueue<Runnable>) arrayBlockingQueue, (r, executor) -> {
            try {
                arrayBlockingQueue.put(r);
            } catch (InterruptedException e) {
                log.error("执行拒绝策略添加阻塞队列失败，{}", e.getMessage());
            }
        });
        log.info("任务线程池初始化完成，核心数:{}, 线程数上线:{}，任务队列上限:{}", corePoolSize, maxPoolSize, queueSize);
    }

    /**
     * 往线程池添加任务，执行任务
     * @param pipelineNode
     * @param args
     */
    public void addTask(PipelineNode pipelineNode, Object args) {
        threadPoolExecutor.execute(() -> pipelineNode.service(args));
    }

}
